import * as APIs from '../../apis/customPage';
import IndexAPI from '../../apis';
import { action, observable, toJS, computed } from 'mobx'
import _ from 'lodash';
import { message } from "antd";
import { replaceE8Url } from '../../util';
import CardStore from '../card';
import  ListStore from '../list';
import { TreeStore } from '../tree';
import ReplyStore from '../reply';
import { isFromProtal } from '../../util/cubeUtil';

export class CustomPageStore {
    @observable loading = false;
    @observable detailData: any = [];
    @observable selectedKey: string = "";
    @observable title: string = "";
    @observable params: any = {};
    @observable iframeHref: string = "";
    @observable windowTitle: string = "";
    @observable mainFrameRefVisible: boolean = true;
    @observable isCube: boolean = false;

    @observable isSearchShow: boolean = false;
    @observable isCardShow: boolean = false;
    @observable isShowReply: boolean = false;
    @observable isTreeShow:boolean = false;

    @observable card: CardStore = new CardStore();
    @observable search = ListStore;
    @observable tree: TreeStore = new TreeStore();
    // @observable customPage: CustomPageStore;
    @observable reply: ReplyStore= new ReplyStore();
    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
      }
    @observable showMoreCountData: boolean = false; //是否显示下拉列表中的查询统计数据

    @action
    updateParams = (params: any) => {
        let temp = !_.isEqual(toJS(this.params), params);
        this.params = params;
        if (temp) {
            this.getCustomPageViewData(params);
            this.getIconInfo(params.id);
        }
    }

    @action
    getCustomPageViewData = (params) => {
        this.loading = true;
        APIs.getCustomPageViewData(params).then(action(({ status, error, defaultActiveKey, Customname, detail,windowTitle='' }) => {
            if (status == "1") {
                this.selectedKey = defaultActiveKey;
                if(!isFromProtal()){
                    this.windowTitle = windowTitle;
                }
                this.detailData = detail;
                this.title = Customname;
                this.iframeHref = this.getAddress(defaultActiveKey, detail,params);
            } else {
                message.error(error);
                throw error;
            }
            this.loading = false;
        }
        ));
    }

    @action
    tabChange = (key: string,query) => {
        this.selectedKey = key;
        this.iframeHref = this.getAddress(key, toJS(this.detailData),query);
        //关闭列表上左滑，滑动出来的卡片
        (window as any).showSearchSlideModal &&(window as any).showSearchSlideModal(false,"","");
    }

    getAddress = (key: string, data: any,params) => {
        let href: string = "";
        let iframeurl: string = "";
        data && data.map(item => {
            if (item.detailid == key) {
                href = item.hrefaddress;
            }
        });
        this.isCube = false;
        if (href) {
            let url = replaceE8Url(href);
            //链接参数处理
            if(params){
                _.keys(params).forEach(item=>{
                    url=url.replace('$'+item+'$',params[item]);
                });
            }
            if(url.indexOf('/spa/cube') > -1){ //针对建模模块的地址处理
                if (url.indexOf('?') > -1) {
                    iframeurl = url.split('?').join('?hidetop=1&istree=true&_t='+new Date().getTime()+'&');
                } else {
                    iframeurl = `${url}?hidetop=1&istree=true&_t=${new Date().getTime()}`;
                }
            }else if(url.indexOf('/spa/edc/static/app') > -1){ //数据中心的链接
                ///spa/edc/static/app/index.html?boardId=a5050d0437b04875aa771ce0e95e91a4#/edc/dataBoard
                iframeurl = url.split('?').join('?_t='+new Date().getTime()+'&');
            }else{
                iframeurl = url;
            }
           
            if (url.indexOf("/spa/cube/index.html") >= 0) {

                this.isCube = true;
                if (url.indexOf("main/cube/card") >= 0) {
                    iframeurl = iframeurl+'&noTitleShow=1'
                    this.isSearchShow = false;
                    this.isShowReply = false;
                    this.isTreeShow = false;
                    this.showCard(iframeurl);
                } else if (url.indexOf("main/cube/search") >= 0) {
                    iframeurl = iframeurl+'&menuIds=1'
                    this.isCardShow = false;
                    this.isShowReply = false;
                    this.isTreeShow = false;
                    this.showSearch(iframeurl);
                } else if (url.indexOf("main/cube/tree") >= 0) {
                    iframeurl = iframeurl+'&noTitleShow=1'
                    this.isSearchShow = false;
                    this.isCardShow = false;
                    this.isShowReply = false;
                    this.showTree(iframeurl);
                } else if (url.indexOf("main/cube/reply") >= 0) {
                    this.isSearchShow = false;
                    this.isCardShow = false;
                    this.isTreeShow = false;
                    this.showReply(iframeurl);
                } else {
                    this.isCube = false;
                }
                this.mainFrameRefVisible = false;
            }
            if (!this.isCube) {
                this.isSearchShow = false;
                this.isCardShow = false;
                this.isShowReply = false;
                this.isTreeShow = false;
                const mainFrame = document.getElementById("cube-custompage-div") as HTMLIFrameElement;
                if (mainFrame) {
                    mainFrame.src = iframeurl;
                    this.mainFrameRefVisible = true;
                }
            }
        }
        return href;
    }
    @computed
    get rightMenus(): any[] {
        if (this.isSearchShow) {
            return this.search.rightMenus.map(m => ({
                key: m.key,
                content: m.name,
                icon: <i className={m.icon} />,
                quickButton: m.quickButton,
            }));
        } else if (this.isCardShow) {
            return this.card.cardTab.rightMenus.map(m => ({
                ...m,
                disabled: this.card.cardTab.disabled
            }));
        }
        return []
    }

    @action
    rightMenuHandle = (key: string) => {
        if (this.isSearchShow) {
            this.search.rightMenuClick(key);
        } else if (this.isCardShow) {
            this.card.Actions.runCustomAction(key);
        }
    }

    @computed
    get getTitle(): string {
        // if (this.isSearchShow) {
        //     return this.search.top.name;
        // } else if (this.isCardShow) {
        //     return this.card.cardTab.title;
        // }
        return this.title
    }
    @action
    getQuery = (href: string) => {
        const lastofnum = href.lastIndexOf('?');
         href = href.slice(lastofnum);
        const query = href.split('?')[1];
        const querys = query.split("&");
        const queryObj: any = {};
        querys.map(q => {
            const [name, value] = q.split("=");
            _.set(queryObj, name, value);
        });
        return queryObj;
    }

    @action
    showSearch = (href: string) => {
        this.isSearchShow = true;
        this.search.isInnerTab = true;
        this.search.reloadSearch(this.getQuery(href));
    }

    @action
    showCard = (href: string) => {
        this.isCardShow = true;
        this.card.isInline = true;
        if (!this.card) {
            this.card = new CardStore();
        }
        this.card.reloadSearch(this.getQuery(href));
    }

    @action
    showReply = (href: string) => {
        this.isShowReply = true;
        this.reply.updateParams(this.getQuery(href));
    }

    @action
    showTree =(href: string) =>{
        this.isTreeShow = true;
        this.tree.updateParams(this.getQuery(href));
    }


    @action
    clearStatus = () => {
        this.detailData = [];
        this.selectedKey = "";
        this.title = "";
        this.params = {};
        this.iframeHref = "";
        this.mainFrameRefVisible = true;
        this.isCube = false;
    }

    @action
    getIconInfo = (pageid) => {
        IndexAPI.getAppInfoByID({ pageid }).then((data: any) => {
            if (data.status == "1") {
                this.iconInfo = {
                    icon: data.icon || "icon-coms-ModelingEngine",
                    iconColor: data.iconColor || "#fff",
                    iconBg: data.iconBg || "#96358a"
                };
            }
        })
    }

    /* 是否显示‘统计’下拉列表 */
    @action
    handleShowMoreCountData = (showMoreCountData) => {
        this.showMoreCountData = !showMoreCountData;
    }
}
export default new CustomPageStore();
